<script>
	import { Notyf } from 'notyf';
	import { onMount } from 'svelte';
	import { writable } from 'svelte/store';

	const currentPage = writable('userManagement');

	//------------------------------------------------------

	let userData1 = [];
	let userData2 = [];
	let isAdding = false;
	let isEditing = false;
	let editingUser = null;
	let newUserType = 'comuser';
	let newUsername = '';
	let newEmail = '';
	let newPhoneNumber = '';
	let newIDNumber = '';
	let newPassword = '';
	let notyf;

	onMount(async () => {
		notyf = new Notyf({
			duration: 3000,
			className: 'x-notification',
			position: { x: 'right', y: 'top' }
		});
		// 检查是否已经刷新过
		if (!sessionStorage.getItem('refreshed')) {
			sessionStorage.setItem('refreshed', 'true');
			window.location.reload();
		} else {
			sessionStorage.removeItem('refreshed');
		}
		refreshBackgroundImage();
		fetchUsers();
	});

	function refreshBackgroundImage() {
		const body = document.querySelector('body');
		const timestamp = new Date().getTime();
		body.style.backgroundImage = `url('/bluesky.png?timestamp=${timestamp}')`;
	}

	async function fetchUsers() {
		try {
			const response = await fetch('/api/admin/userinfo', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			//console.log(data);
			userData1 = Array.isArray(data) ? data : [data];
			// console.log(userData1[0]);
			if (userData1[0] == null) {
				userData1 = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}

		try {
			const response = await fetch('/api/admin/businessinfo', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			//console.log(data);
			userData2 = Array.isArray(data) ? data : [data];
			if (userData2[0] == null) {
				userData2 = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
			userData2 = [];
		}
	}

	async function switchPage(page) {
		currentPage.set(page);
		if (page === 'userManagement') {
			fetchUsers();
		}
		if (page === 'shopManagement') {
			fetchShops();
			setTimeout(() => {
				fetchGood();
			}, 500);
		}
		if (page === 'turnoverManagement') {
			fetchPurchase();
		}
		if (page === 'discusstionManagement') {
			fetchComments();
		}
	}

	function startAdding() {
		isAdding = true;
		resetForm();
	}

	function cancelAdd() {
		isAdding = false;
		resetForm();
	}

	//增加用户函数
	function confirmAdd() {
		fetch('/api/admin/usermgr', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				userType: newUserType,
				username: newUsername,
				email: newEmail,
				phonenumber: newPhoneNumber,
				idnumber: newIDNumber,
				password: newPassword
			})
		})
			.then((response) => {
				if (!response.ok) {
					throw new Error('Network response was not ok');
				}
				fetchUsers();
				notyf.success('添加用户成功');
			})
			.catch((error) => {
				notyf.error('添加用户失败');
				console.error('Error adding user:', error);
			});
		isAdding = false;
		resetForm();
	}

	//修改用户函数
	function confirmEdit() {
		fetch('/api/admin/usermgr', {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				userType: editingUser.userType,
				username: editingUser.username,
				email: editingUser.email,
				phonenumber: editingUser.phonenumber,
				idnumber: editingUser.idnumber,
				password: editingUser.password
			})
		})
			.then((response) => {
				if (!response.ok) {
					throw new Error('修改用户失败');
				}
				fetchUsers();

				notyf.success('修改用户成功');
			})
			.catch((error) => {
				notyf.error('修改用户失败');
				console.error('Error editing user:', error);
			});
		isEditing = false;
		editingUser = null;
	}

	//删除用户函数
	function deleteUser(user) {
		fetch('/api/admin/usermgr', {
			method: 'DELETE',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				userType: user.userType,
				username: user.username,
				email: user.email,
				phonenumber: user.phonenumber,
				idnumber: user.idnumber,
				password: user.password
			})
		})
			.then((response) => {
				if (!response.ok) {
					throw new Error('删除用户失败');
				}

				notyf.success('删除用户成功');
				fetchUsers();
			})
			.catch((error) => {
				notyf.error('删除用户失败');
				console.error('Error deleting user:', error);
			});
	}

	function startEditing(user) {
		isEditing = true;
		editingUser = { ...user };
	}

	function cancelEdit() {
		isEditing = false;
		editingUser = null;
	}
	function resetForm() {
		newUserType = 'comuser';
		newUsername = '';
		newEmail = '';
		newPhoneNumber = '';
		newIDNumber = '';
		newPassword = '';
	}

	//------------------------------------------------------
	let shopData1 = [];
	let shopData2 = [];

	//获取商店信息
	async function fetchShops() {
		try {
			const response = await fetch('/api/admin/shopaudit', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			shopData1 = Array.isArray(data) ? data : [data];
			// console.log(shopData1[0]);
			if (shopData1[0] == null) {
				shopData1 = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}

		try {
			const response = await fetch('/api/admin/shopmgr', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			shopData2 = Array.isArray(data) ? data : [data];
			if (shopData2[0] == null) {
				shopData2 = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	// xiam
	// 同意申请开店
	async function allowsubmit(shop) {
		try {
			const response = await fetch('/api/admin/shopaudit', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					shopname: shop.shopname
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchShops();
			notyf.success('同意申请开店成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}
	// 不同意申请开店
	async function disallowsubmit(shop) {
		try {
			const response = await fetch('/api/admin/shopaudit', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					shopname: shop.shopname
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchShops();
			notyf.success('不同意申请开店成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}
	// 下架商店
	async function outshop(shop) {
		try {
			const response = await fetch('/api/admin/shopmgr', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					shopname: shop.shopname
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchShops();
			notyf.success('下架商店成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	let goodData = [];

	// 获取商城内所有商品
	async function fetchGood() {
		try {
			const response = await fetch('/api/admin/goodmgr', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			goodData = Array.isArray(data) ? data : [data];
			// console.log(goodData[0]);
			if (goodData[0] == null) {
				goodData = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	// 下架商品
	async function outgood(good) {
		try {
			const response = await fetch('/api/admin/goodmgr', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					shopname: good.shopname,
					goodname: good.goodname,
					goodprice: good.goodprice,
					goodcount: good.goodcount
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchGood();
			notyf.success('下架商店成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	let buyData = [];

	// 获取所有流水
	async function fetchPurchase() {
		try {
			const response = await fetch('/api/admin/purchaseinfomgr', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			buyData = Array.isArray(data) ? data : [data];
			// console.log(buyData[0]);
			if (buyData[0] == null) {
				buyData = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	async function deletebuy(buy) {
		try {
			const response = await fetch('/api/admin/purchaseinfomgr', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					username: buy.username,
					shopname: buy.shopname,
					goodname: buy.goodname,
					goodcount: buy.goodcount,
					goodprice: buy.goodprice,
					cost: buy.cost
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchPurchase();
			notyf.success('删除流水成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	// 下面是评论管理功能
	let commentData = [];
	async function fetchComments() {
		try {
			const response = await fetch('/api/admin/commentmgr', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			commentData = Array.isArray(data) ? data : [data];
			//console.log(commentData[0]);
			if (commentData[0] == null) {
				commentData = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	async function deletecomment(comment) {
		try {
			const response = await fetch('/api/admin/commentmgr', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					time: comment.time,
					username: comment.username,
					shopname: comment.shopname,
					goodname: comment.goodname,
					text: comment.text
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			fetchComments();
			notyf.success('删除评论成功');
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}
</script>

<div id="sidebar">
	<button on:click={() => switchPage('userManagement')}>用户管理</button>
	<button on:click={() => switchPage('shopManagement')}>商店管理</button>
	<button on:click={() => switchPage('turnoverManagement')}>流水管理</button>
	<button on:click={() => switchPage('discusstionManagement')}>评论管理</button>
</div>

<div id="content">
	{#if $currentPage === 'userManagement'}
		<div id="user-management-container">
			<h2>用户管理</h2>
			<div>
				<h3>普通用户表</h3>
				<table class="user-info">
					<thead>
						<tr>
							<th>UserType</th>
							<th>Username</th>
							<th>Email</th>
							<th>PhoneNumber</th>
							<th>IDNumber</th>
							<th>Password</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						{#each userData1 as user}
							<tr>
								<td>{user.userType}</td>
								<td>{user.username}</td>
								<td>{user.email}</td>
								<td>{user.phonenumber}</td>
								<td>{user.idnumber}</td>
								<td>{user.password}</td>
								<td>
									<div class="button-group">
										<button class="edit" on:click={() => startEditing(user)}>编辑</button>
										<button class="delete" on:click={() => deleteUser(user)}>删除</button>
									</div>
								</td>
							</tr>
						{/each}
						{#if userData1.length === 0}
							<tr>
								<td colspan="7">No users found</td>
							</tr>
						{/if}
					</tbody>
				</table>
			</div>
			<div>
				<h3>商业用户表</h3>
				<table class="user-info">
					<thead>
						<tr>
							<th>UserType</th>
							<th>Username</th>
							<th>Email</th>
							<th>PhoneNumber</th>
							<th>IDNumber</th>
							<th>Password</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						{#each userData2 as user}
							<tr>
								<td>{user.userType}</td>
								<td>{user.username}</td>
								<td>{user.email}</td>
								<td>{user.phonenumber}</td>
								<td>{user.idnumber}</td>
								<td>{user.password}</td>
								<td>
									<div class="button-group">
										<button class="edit" on:click={() => startEditing(user)}>编辑</button>
										<button class="delete" on:click={() => deleteUser(user)}>删除</button>
									</div>
								</td>
							</tr>
						{/each}
						{#if userData2.length === 0}
							<tr>
								<td colspan="7">No users found</td>
							</tr>
						{/if}
					</tbody>
				</table>
			</div>
			<button id="add-user-button" on:click={startAdding}>添加用户</button>

			{#if isAdding}
				<div class="form-container add-form">
					<h2>添加用户</h2>
					<select class="input" bind:value={newUserType}>
						<option value="comuser">comuser</option>
						<option value="business">business</option>
					</select>
					<input type="text" class="input" placeholder="Username" bind:value={newUsername} />
					<input type="email" class="input" placeholder="Email" bind:value={newEmail} />
					<input type="text" class="input" placeholder="PhoneNumber" bind:value={newPhoneNumber} />
					<input type="text" class="input" placeholder="IDNumber" bind:value={newIDNumber} />
					<input type="password" class="input" placeholder="Password" bind:value={newPassword} />
					<button class="button is-primary" on:click={confirmAdd}>确定</button>
					<button class="button" on:click={cancelAdd}>取消</button>
				</div>
			{/if}
		</div>

		{#if isEditing && editingUser}
			<div class="form-container edit-form">
				<label for="editUserType">用户类型</label>
				<select class="input" id="editUserType" bind:value={editingUser.userType} disabled>
					<option value="comuser">comuser</option>
					<option value="business">business</option>
				</select>
				<label for="editUsername">用户名</label>
				<input type="text" class="input" id="editUsername" bind:value={editingUser.username} />
				<label for="editEmail">电子邮件</label>
				<input type="email" class="input" id="editEmail" bind:value={editingUser.email} />
				<label for="editPhoneNumber">电话号码</label>
				<input
					type="text"
					class="input"
					id="editPhoneNumber"
					bind:value={editingUser.phonenumber}
				/>
				<label for="editIDNumber">身份证号</label>
				<input type="text" class="input" id="editIDNumber" bind:value={editingUser.idnumber} />
				<label for="editPassword">密码</label>
				<input type="password" class="input" id="editPassword" bind:value={editingUser.password} />
				<button class="button is-primary" on:click={confirmEdit}>确认修改</button>
				<button class="button" on:click={cancelEdit}>取消</button>
			</div>
		{/if}
	{/if}
	{#if $currentPage === 'shopManagement'}
		<div id="shop-management-container">
			<h2>商店管理</h2>
			<div>
				<h3>待审核的商店</h3>
				<table class="user-info">
					<thead>
						<tr>
							<th>Shopname</th>
							<th>Category</th>
							<th>Idnumber</th>
							<th>Introduce</th>
							<th>Address</th>
							<th>Money</th>
							<th>Createtime</th>
							<th>State</th>
							<th>Owner</th>
							<th>Image</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						{#each shopData1 as shop}
							<tr>
								<td>{shop.shopname}</td>
								<td>{shop.category}</td>
								<td>{shop.idnumber}</td>
								<td>{shop.introduce}</td>
								<td>{shop.address}</td>
								<td>{shop.money}</td>
								<td>{shop.createtime}</td>
								<td>{shop.state}</td>
								<td>{shop.owner}</td>
								<td
									><img
										src={'/shopimage/' + shop.imagename}
										alt=""
										style="width: 100px; height: 100px;"
									/></td
								>
								<td>
									<div class="button-group">
										<button class="edit" on:click={() => allowsubmit(shop)}>同意</button>
										<button class="delete" on:click={() => disallowsubmit(shop)}>取消</button>
									</div>
								</td>
							</tr>
						{/each}
						{#if shopData1.length === 0}
							<tr>
								<td colspan="11">No elem found</td>
							</tr>
						{/if}
					</tbody>
				</table>
			</div>
			<div>
				<h3>开张的商店</h3>
				<table class="user-info">
					<thead>
						<tr>
							<th>Shopname</th>
							<th>Category</th>
							<th>Idnumber</th>
							<th>Introduce</th>
							<th>Address</th>
							<th>Money</th>
							<th>Createtime</th>
							<th>State</th>
							<th>Owner</th>
							<th>Image</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						{#each shopData2 as shop}
							<tr>
								<td>{shop.shopname}</td>
								<td>{shop.category}</td>
								<td>{shop.idnumber}</td>
								<td>{shop.introduce}</td>
								<td>{shop.address}</td>
								<td>{shop.money}</td>
								<td>{shop.createtime}</td>
								<td>{shop.state}</td>
								<td>{shop.owner}</td>
								<td
									><img
										src={'/shopimage/' + shop.imagename}
										alt=""
										style="width: 100px; height: 100px;"
									/></td
								>
								<td>
									<div class="button-group">
										<button class="delete" on:click={() => outshop(shop)}>下架商店</button>
									</div>
								</td>
							</tr>
						{/each}
						{#if shopData2.length === 0}
							<tr>
								<td colspan="11">No elem found</td>
							</tr>
						{/if}
					</tbody>
				</table>
			</div>
			<div>
				<h3>上架的商品</h3>
				<table class="user-info">
					<thead>
						<tr>
							<th>Shopname</th>
							<th>Goodname</th>
							<th>Goodprice</th>
							<th>Goodcount</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						{#each goodData as good}
							<tr>
								<td>{good.shopname}</td>
								<td>{good.goodname}</td>
								<td>{good.goodprice}</td>
								<td>{good.goodcount}</td>
								<td>
									<div class="button-group">
										<button class="delete" on:click={() => outgood(good)}>下架货物</button>
									</div>
								</td>
							</tr>
						{/each}
						{#if goodData.length === 0}
							<tr>
								<td colspan="5">No elem found</td>
							</tr>
						{/if}
					</tbody>
				</table>
			</div>
		</div>
	{/if}
	{#if $currentPage === 'turnoverManagement'}
		<div id="shop-management-container">
			<h2>流水管理</h2>
			<table class="user-info">
				<thead>
					<tr>
						<th>Consumer</th>
						<th>Shopname</th>
						<th>Goodname</th>
						<th>Buycount</th>
						<th>Goodprice</th>
						<th>Cost</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					{#each buyData as buy}
						<tr>
							<td>{buy.username}</td>
							<td>{buy.shopname}</td>
							<td>{buy.goodname}</td>
							<td>{buy.goodcount}</td>
							<td>{buy.goodprice}</td>
							<td>{buy.cost}</td>
							<td>
								<div class="button-group">
									<button class="delete" on:click={() => deletebuy(buy)}>删除记录</button>
								</div>
							</td>
						</tr>
					{/each}
					{#if buyData.length === 0}
						<tr>
							<td colspan="7">No elem found</td>
						</tr>
					{/if}
				</tbody>
			</table>
		</div>
	{/if}
	{#if $currentPage === 'discusstionManagement'}
		<div id="shop-management-container">
			<h2>评论管理</h2>
			<table class="user-info">
				<thead>
					<tr>
						<th>Time</th>
						<th>Username</th>
						<th>Shopname</th>
						<th>Goodname</th>
						<th>Comment</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					{#each commentData as comment}
						<tr>
							<td>{comment.time}</td>
							<td>{comment.username}</td>
							<td>{comment.shopname}</td>
							<td>{comment.goodname}</td>
							<td>{comment.text}</td>
							<td>
								<div class="button-group">
									<button class="delete" on:click={() => deletecomment(comment)}>删除记录</button>
								</div>
							</td>
						</tr>
					{/each}
					{#if commentData.length === 0}
						<tr>
							<td colspan="6">No elem found</td>
						</tr>
					{/if}
				</tbody>
			</table>
		</div>
	{/if}
</div>

<style>
	@import 'notyf/notyf.min.css';
	:global(body) {
		margin: 0;
		font-family: Arial, sans-serif;
		display: flex;
		height: 100vh;
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}

	#sidebar {
		width: 35px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 20px;
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		transition: width 0.3s;
	}

	#sidebar:hover {
		width: 200px;
	}

	#sidebar button {
		width: 100%;
		padding: 10px;
		margin: 10px 0;
		border: none;
		background-color: #007bff;
		color: white;
		font-size: 16px;
		border-radius: 5px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	#sidebar button:hover {
		background-color: #0056b3;
	}

	#content {
		flex-grow: 1;
		padding: 20px;
		margin-left: 35px;
		overflow-y: auto;
	}

	h2 {
		margin-top: 0;
	}

	table.user-info {
		width: 100%;
		border-collapse: collapse;
		margin-top: 10px;
	}

	table.user-info th,
	table.user-info td {
		border: 1px solid #ddd;
		padding: 8px;
		text-align: center;
	}

	table.user-info th {
		background-color: #f2f2f2;
	}

	.button-group {
		display: flex;
		justify-content: center;
	}

	.button-group button {
		margin: 0 5px;
		padding: 5px 10px;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.button-group button.edit {
		background-color: #4caf50;
		color: white;
	}

	.button-group button.edit:hover {
		background-color: #45a049;
	}

	.button-group button.delete {
		background-color: #f44336;
		color: white;
	}

	.button-group button.delete:hover {
		background-color: #da190b;
	}

	#add-user-button {
		margin-top: 10px;
		padding: 10px 20px;
		background-color: #007bff;
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	#add-user-button:hover {
		background-color: #0056b3;
	}

	.form-container {
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding: 20px;
		border-radius: 5px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		background-color: rgba(255, 255, 255, 0.8);
	}

	.form-container.add-form {
		margin-top: 20px;
	}

	.form-container.edit-form {
		position: fixed;
		top: 20px;
		right: 20px;
		width: 300px;
	}

	.input {
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
		font-size: 16px;
	}

	.button {
		padding: 10px;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.button.is-primary {
		background-color: #007bff;
		color: white;
	}

	.button.is-primary:hover {
		background-color: #0056b3;
	}

	.button:not(.is-primary) {
		background-color: #6c757d;
		color: white;
	}

	.button:not(.is-primary):hover {
		background-color: #5a6268;
	}
</style>
